// pages/model/model.js
var app = getApp();
var touchDot = 0;//触摸时的原点
var i=0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    image: ['/image/bg1.jpg', '/image/bg2.jpg','/image/bg3.jpg'],
    length:3,//模板中图片的长度
    show:1,//当前显示的图片，从1开始
    first:true,
    animationData: {},
    up:true,
    video:false,
    music:false,
    text:true,
    video:'',
    imgs:[],
    index_content:[],
    come:true,
    tanmutext:'弹',
    lock:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var res = wx.getSystemInfoSync();
    that.setData({
      width: res.screenWidth,
      height: res.screenHeight,
      options:options
    })
    that.getData();
  },
  getData:function(res){
    var that = this;
    app.getLoginSession(function (session) {
      wx.request({
        url: app.api + '/index/design',
        data:{
          id:that.data.options.id,
          t_session:session
        },
        success:function(res){
          var res = res.data;
          if(res.done){
            var data = res.retval;
            that.setData({
              data:data,
              loading:false
            })
            that.music();
          }else{
            that.setData({
              errorTips: '接口请求失败',
              loading: true
            })
          }
        },
        fail:function(res){
          that.setData({
            errorTips: '接口请求失败',
            loading: true
          })
        }
      })
  })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    // var that = this;
    // console.log(res);
    // if (res=='button') {
    //   wx.getUserInfo({
    //     success: function (res) {
    //       that.setData({
    //         name: res.userInfo.nickName
    //       })
    //     }
    //   })
    //   return {
    //     title: that.data.name+'自定义转发标题',
    //     path: '/page/cart/cart?id=6',
    //     success: function (res) {
    //       // 转发成功
    //     },
    //     fail: function (res) {
    //       // 转发失败
    //     }
    //   }
    // }else{
    //   return {
    //     title: that.data.name + '自定义转发标题',
    //     path: '/page/cart/cart?id=6',
    //     success: function (res) {
    //       // 转发成功
    //     },
    //     fail: function (res) {
    //       // 转发失败
    //     }
    //   }
    // }
  },
  // 触摸开始事件
  touchStart: function (e) {
    var that = this;
    touchDot = e.touches[0].pageY; // 获取触摸时的原点
    if(that.data.first==true){
      that.setData({
        first: false
      })
    }
  },
  // 触摸结束事件
  touchEnd: function (e) {
    var that = this;
    var touchMove = e.changedTouches[0].pageY;
    console.log(touchMove);
    // 向上滑动，下一页   
    if (touchDot - touchMove >=10 ) {
        if(that.data.length > that.data.show){
          that.setData({
            show:that.data.show+1,
            first:false,
            up:true
          })
          console.log(that.data.show);
        }
    }
    // 向下滑滑动，上一页
    if (touchMove - touchDot >= 10) {
      console.log("上一页");
      if (that.data.show>1) {
        that.setData({
          show: that.data.show - 1
        })
      }
    }
  },
  //播放、暂停
  start: function (res) {
    var that = this;
    console.log(res);
    that.setData({
      music: true
    })
  },
  stop:function(){
    var that = this;
    that.setData({
      music: false
    })
  },
  //输入框的显示与隐藏
  input_text:function(){
    var that = this;
    that.setData({
      text:false
    })
  },
  //获取用户输入
  input:function(res){
    var that = this;
    that.data.data.blessing=res.detail.value;
    that.setData({
      data:that.data.data
    })
  },
  submit_input:function(res){
    var that = this;
    that.setData({
      text: true
    })
  },
  onShow:function(){
    if(this.data.come!=true){
      this.music();
    }else{
      this.setData({
        come:false
      })
    }
  },
  music:function(res){
    this.audioCtx = wx.createAudioContext('myAudio')
    this.audioCtx.setSrc(this.data.data.audio)
    this.audioCtx.play()
    this.videoContext = wx.createVideoContext('myVideo')
  },
  audioPause: function () {
    this.audioCtx.pause()
  },
  videoPause: function () {
    this.videoContext.pause()
  },
  //返回上一页
  navback:function(res){
    var that = this;
    wx.navigateBack({
      delta: 1
    })
  },
  //选择图片或者视频
  select: function (res) {
    var that = this;
    var index = parseInt(res.currentTarget.dataset.index);
    var type = res.currentTarget.dataset.type;
    if (type == "video") {
      wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 10,
        camera: 'back',
        success: function (res) {
          console.log(res);
          that.data.index_content[index] = res.tempFilePath
          that.setData({
            index_content: that.data.index_content
          })
          that.upload(res.tempFilePath, index+1);
        }
      })
    } else {
      wx.chooseImage({
        count: 1, // 默认9
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {
          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          var tempFilePaths = res.tempFilePaths[0]
          that.data.index_content[index] = tempFilePaths
          that.setData({
            index_content: that.data.index_content
          })
          that.upload(res.tempFilePaths[0], index+1);
        }
      })
    }
  },
  //把视频或图片上传到服务器
  upload:function(file,i){
    var that = this;
    wx.uploadFile({
      url: app.api + '/index/uploadFile',
      filePath: file,
      name: 'file',
      formData: {
        file: file
      },
      method: 'POST',
      header: {
        'content-type': 'multipart/form-data'
      },
      success: function (res) {
        console.log(i);
        var data = JSON.parse(res.data);
        var file = data.retval.file_path;
        var img = that.data.imgs;
        var mp4 = that.data.video;
        console.log(file.split("."));
        if (file.split(".")[1] != "mp4") {
          img.push({
            url: file,
            sort: i,
          });
          that.setData({
            imgs: img,
          })
          console.log(that.data.imgs);
        } else {
          mp4 = file;
          that.setData({
            video: mp4
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '上传失败！',
          icon:'loading'
        })
      }
    })
  },
  //完成
  submit: function (res) {
    var that = this;
    if(that.data.imgs.length!=0||that.data.video.length!=0){
      if (!that.data.lock){
        that.setData({
          lock: true
        })
        app.getLoginSession(function (session) {
          console.log("提交");
          console.log(that.data.options.id);
          console.log(session);
          wx.request({
            url: app.api + '/Card/create',
            data: {
              t_session: session,
              design_id: that.data.options.id,
              blessing: that.data.data.blessing,
              photos: that.data.imgs,
              video: that.data.video
            },
            method: 'POST',
            header: {
              'content-type': 'application/json' // 默认值
            },
            success: function (res) {
              if (res.data.done && res.data.retval.id != null) {
                console.log("贺卡id");
                console.log(res.data.retval.id);
                wx.navigateTo({
                  url: '/pages/cart_' + that.data.data.css_template + '/cart?id=' + res.data.retval.id + '&&from=model',
                })
              } else {
                wx.showModal({
                  title: '提示',
                  content: res.data.retval.msg,
                })
                that.setData({
                  lock: false
                })
              }
            },
            fail: function (res) {
              that.setData({
                lock: false
              })
              wx.showToast({
                title: '请重试！',
                icon: 'loading'
              })
            }
          })
        })
      }
    }else{
      wx.showModal({
        title: '提示',
        content: '请点击图片或视频上传您的照片或者视频',
      })
    }
   
  },
  onHide: function (res) {
    this.audioPause();
    this.videoPause();
    this.setData({
      lock: false
    })
  },
  onUnload: function (res) {
    this.audioPause();
    this.videoPause();
    this.setData({
      lock: false
    })
  }
})